import * as Cesium from 'cesium';
import gisTools from '../GisTools';
import mouseHelper from '../MouseHelper';
//当前类使用的全局的viewer
let cviewer: any = {};
//当前类的事件句柄
let handler: any = {};
/**
 * 添加、清除、连续添加测试过
 */
class DrawPolygon {
  _drawingPolygon: any;
  _drawingPolyline: any;
  _drawingPositions: any;
  _drawingEntity:any;
  isDrawingEnd: any;
  drawedPositions: any;
  drawedGraphics: any;
  constructor(viewer: any) {
    //绘制中的graphic-主要绘制活动的面使用   活动的面  --- 脏数据
    this._drawingPolygon = null;
    //活动的线
    this._drawingPolyline=null;
    //绘制中的geometry-主要绘制面、线使用  -数据类型 Cartesian3  ---脏数据
    this._drawingPositions = [];
    //绘制过程中顶点，以及点数不足三个点时的线都放在内部 --脏数据
    this._drawingEntity=[]
    //绘制完成的graphics 数组 Array<any>
    this.drawedGraphics = [];
    //绘制完成的geometry  -数据类型 [Array<Cartesian3>]
    this.drawedPositions = [];
    //是否绘制结束
    this.isDrawingEnd = false;
    cviewer = viewer;
    handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  }

  /**
   * 开始绘制
   * @param bNeed  true | false  表示绘制动作是否是连续性的，即绘制完一个不结束，默认false
   * @param options  {
   *   "Polygon":{ fill:"填充颜色","opacity":"透明度","stroken":"线颜色","width":"线宽度" }
   *   "Polyline":{ "stroken":"线颜色","width":"线宽度" }   //绘制面的时候有填充
   *        "popOffset":{x:400,y:0}
   * }
   */
  startDraw(bNeed: boolean=false, options: any={}) {
    this.clearDrawGraphic();
    let _this = this;
    let { popOffset,Polyline,Polygon } = options;
    mouseHelper.createHelper({ x:-500,y:-500 }, '',popOffset);
    //左键事件
    handler.setInputAction(function(evt: any) {
      let car3 = gisTools.getCar3Position(cviewer,evt.position);
      if(car3){
        if(_this._drawingPositions.length===0){
          _this._drawingPositions.push(car3.clone());
        }
        _this._drawingPositions.push(car3);
        _this.createPoint(car3.clone());
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    //鼠标移动事件
    handler.setInputAction(function(evt: any) {
      let car3 = gisTools.getCar3Position(cviewer,evt.endPosition);
        if (_this._drawingPositions.length===0) {
          mouseHelper.updateHelper(evt.endPosition, '左键点击开始绘制',popOffset);
        }
        if (_this._drawingPositions.length > 0  && _this._drawingPositions.length < 4  ) {
          mouseHelper.updateHelper(evt.endPosition, '左键点击继续绘制',popOffset);
        }
        if (_this._drawingPositions.length >= 4) {
          mouseHelper.updateHelper(evt.endPosition, '左键点击继续绘制，右键点击结束绘制',popOffset);
        }
        if(_this._drawingPositions.length>0){
          _this._drawingPositions.pop();
          _this._drawingPositions.push(car3);
          console.log("当前选择的",_this._drawingPositions)
          if (!_this._drawingPolyline) {
            _this._drawingPolyline = _this.createDynamicPolyline(Polyline);
          }
          if (!_this._drawingPolygon) {
            _this._drawingPolygon = _this.createDynamicPolygon(Polygon);
          }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    //鼠标右键事件
    handler.setInputAction(function(evt: any) {
      let car3 = gisTools.getCar3Position(cviewer,evt.position);
      if(_this._drawingPositions.length>3){
        _this.rightHandler(_this,car3,bNeed)
      }
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }

  rightHandler(_this:any,car3:any,flag:boolean){
    //当前鼠标右键的操作点位记录
    _this._drawingPositions.push(car3);
    //鼠标动态绘制过程的点+1
    // _this._drawingPositions.push(car3);

    let graphic:any= _this.createHasPolygon(_this._drawingPositions)
    //某个图形绘制结束的的存储
    _this.drawedGraphics.push(graphic);
    let graphicline:any= _this.createHasPolyline(_this._drawingPositions)
    //某个图形绘制结束的的存储
    _this.drawedGraphics.push(graphicline);
    //当前图形绘制完的存储
    _this.drawedPositions.push(JSON.parse(JSON.stringify(_this._drawingPositions)));
    // _this.drawedPositions.push(newPoints);
    //右键直接结束创建尾点
    _this.createPoint(car3.clone());
    //动态图形的还原
    _this._drawingPolygon = null;
    _this._drawingPositions = [];
    //如果是一次绘制，绘制结束完，清除事件
    if(!flag){
      _this.isDrawingEnd = true;
      _this.endDrawing();
    }
  }
  /**
   *结束绘制的事件
   */
  endDrawing() {
    if(handler){
      handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    mouseHelper.removeHelper();
    return true;
  }

  /**
   * 清除绘制的Graphic
   */
  clearDrawGraphic() {
    this.endDrawing();
    if(this.drawedGraphics.length>0){
      this.drawedGraphics.forEach((item:any)=>{
        cviewer.entities.remove(item)
      })
    }
    if(this._drawingEntity.length>0){
      this._drawingEntity.forEach((item:any)=>{
        cviewer.entities.remove(item)
      })
    }
    this.isDrawingEnd=false;
    this._drawingPolygon = null;
    this._drawingPositions = [];
    this.drawedPositions=[];
    this.drawedGraphics=[];
    return true;
  }



  /**
   * 创建面
   * @param positionArr-绘制过程中的动态的面
   * @param style
   */
  createDynamicPolygon(style: any) {
    if(!style){
       style={
         fill:'#DC143C',
         opacity:0.1,
         stroken:'#DC143C',
         width:3
       }
    }
    style['fill'] = style?.fill ?? '#DC143C';
    style['opacity'] = style?.opacity ?? 0.1;
    style['stroken'] = style?.stroken ?? '#DC143C';
    style['width'] = style?.width ?? 3;
    let _this = this;
    var polygon = cviewer.entities.add({
      polygon: {
        hierarchy: new Cesium.CallbackProperty(function() {
          return new Cesium.PolygonHierarchy(_this._drawingPositions);
        }, false),
        clampToGround: true,
        show: true,
        fill: true,
        material: Cesium.Color.fromCssColorString(style.fill).withAlpha(style.opacity),
        width: style.width,
        outlineColor: Cesium.Color.fromCssColorString(style.stroken),
        outlineWidth: 1,
        outline: false,
      },
    });
    return polygon;
  }

  /**
   * 创建面
   * @param positionArr-绘制过程中的动态的面
   * @param style
   */
  createHasPolygon(carArr:any) {
    let newCarArr:any=[];
    //避免数据改变（_drawingPositions）的影响
    carArr.forEach((item:any)=>{
      newCarArr.push(item.clone());
    })
   let style={
     fill:'#DC143C',
     opacity:0.5,
     stroken:'#DC143C',
     width:3
   }
    let _this = this;
    var polygon = cviewer.entities.add({
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(newCarArr),
        clampToGround: true,
        show: true,
        fill: true,
        material: Cesium.Color.fromCssColorString(style.fill).withAlpha(style.opacity),
        width: style.width,
        outlineColor: Cesium.Color.fromCssColorString(style.stroken),
        outlineWidth: 1,
        outline: true,
      },
    });
    return polygon;
}

  /**
   * 添加的是多边形的顶点
   * @param cartesian
   */
  createPoint(cartesian:any) {
    var point = cviewer.entities.add({
      position: cartesian,
      point: {
        pixelSize: 10,
        color: Cesium.Color.YELLOW,
      }
    });
    this._drawingEntity.push(point);
    return point;
  }
  /**
   * 添加折线-点数是2个时，绘制的是线
   * @param carArr
   */
  createHasPolyline(carArr:any) {
    let newCarArr:any=[];
    //避免数据改变（_drawingPositions）的影响
    carArr.forEach((item:any)=>{
      newCarArr.push(item.clone());
    })
    //为了线首位相连
    newCarArr.push(newCarArr[0]);
    let style={
      stroken:"#DC143C",
      width:3
    }
    var polyline = cviewer.entities.add({
      polyline: {
        positions: newCarArr,
        show: true,
        material: Cesium.Color.fromCssColorString(style['stroken']),
        width: style['width'],
        clampToGround: true,
      },
    });
    this._drawingEntity.push(polyline);
    return polyline;
  }

  createDynamicPolyline(style:any) {
    if(!style){
      style={
        stroken:"#DC143C",
        width:3
      }
    }
    style['stroken'] = style?.stroken ?? '#DC143C';
    style['width'] = style?.width ?? 3;
    let $this = this;
    let polyline =cviewer.entities.add({
      id: 'area_search_draw_graphic_polygon' + new Date().getTime(),
      polyline: {
        //使用cesium的peoperty
        positions: new Cesium.CallbackProperty(function () {
          let carArr:any=$this._drawingPositions;
          let newCarArr:any=[];
          //避免数据改变（_drawingPositions）的影响
          carArr.forEach((item:any)=>{
            newCarArr.push(item.clone());
          })
          //为了线首位相连
          newCarArr.push(newCarArr[0]);
          return newCarArr
        }, false),
        show: true,
        material: Cesium.Color.RED,
        width: 3,
        clampToGround: true
      }
    });
    return  polyline;
  }

}

export default DrawPolygon;



